﻿using FairyGUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class ShopGoldPage : BasePage
{
    private GList lsItems;

    private GTextField tfTitle;

    public ShopGoldPage(GComponent vie) : base(vie)
    {
        lsItems = this.view.GetChild("n2").asList;
        tfTitle = this.view.GetChild("n1").asTextField;

        lsItems.onClickItem.Add(OnItemClick);
    }

    public override void Show()
    {
        MsgListenerMgr.AddMsgListener(MsgListenerType.BaseInfoChange, OnBaseInfoChange);
        this.Load();
    }

    public override void Close()
    {
        MsgListenerMgr.RemoveMsgListener(MsgListenerType.BaseInfoChange, OnBaseInfoChange);
    }

    private void Load()
    {
        if (lsItems.numChildren > 0)
        {
            return;
        }

        SetTitle();
        lsItems.RemoveChildrenToPool();

        List<InitShop> items = InitShopMgr.GetByType(1);
        for (int i = 0; i < items.Count; i++)
        {
            if (InitItemMgr.Dict.TryGetValue(items[i].item_id, out InitItem initItem))
            {
                GButton button = lsItems.GetFromPool("ui://f2iijc3nldzwi2").asButton;
                button.data = items[i].id;

                GTextField title = button.GetChild("n1").asTextField;
                title.text = initItem.name;
                title.color = CommonUtil.GetItemColor(initItem.quality);

                GTextField tfCount = button.GetChild("n2").asTextField;
                tfCount.SetVar("count", CommonUtil.NumberToString(items[i].price));
                tfCount.FlushVars();
                lsItems.AddChild(button);
                for (int j = 1; j <= 5; j++)
                {
                    GImage cpt = button.GetChild("bg" + j.ToString()).asImage;
                    if (cpt != null)
                    {
                        cpt.visible = j == initItem.quality;
                    }
                }
            }
        }
    }

    private void SetTitle()
    {
        tfTitle.SetVar("count", CommonUtil.NumberToString(GameNetwork.Player.BaseInfo.Gold)).SetVar("info", "挑战关卡");
        tfTitle.FlushVars();
    }

    private void OnBaseInfoChange(object[] para)
    {
        SetTitle();
    }

    private void OnItemClick(EventContext context)
    {
        GButton button = lsItems.GetChildAt(lsItems.selectedIndex).asButton;
        if (button == null)
        {
            return;
        }

        int id = (int)button.data;
        PopupPanelManager.Open<BuyShopPanel>(id);
    }
}
